/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { TaskNames } from '../../common/task-names.js';
import { TargetTaskService } from '../../service/target-task-service.js';
import { OhosHapTask } from '../../task/ohos-hap-task.js';
import { LegacyCompileResource } from '../legacy-compile-resource.js';
import { LegacyPreviewCompileResource } from '../legacy-preview-compile-resource';
import CommonTask = TaskNames.CommonTask;

import { TaskDetails } from '@ohos/hvigor';
import { capitalize } from '@baize/wdk';

import { ModuleTaskService } from '../../service/module-task-service.js';

/**
 * 增加一个忽略feature和entry差异的编译资源的hook任务，用于挂接feature的多个entryModules的任务
 *
 * @since 2022/9/8
 */
export class LegacyHookCompileResource extends OhosHapTask {
  constructor(taskService: TargetTaskService) {
    super(taskService, CommonTask.LEGACY_HOOK_COMPILE_RESOURCE);
  }

  protected doTaskAction(): void {
    // this is a hook task for depends diff task
    // task do nothing
  }

  initTaskDepends(): void {
    const isSupportIncrement: boolean = this.sdkInfo.isPreviewCompileResourceIncrement(this.targetData.isHarmonyOS());
    const taskName: string = isSupportIncrement ? LegacyPreviewCompileResource.name : LegacyCompileResource.name;
    const moduleType = this.moduleModel.getModuleType();
    const relatedEntryModules = this.moduleModel.getRelatedEntryModules();
    if (ModuleTaskService.checkEntryModules(moduleType, relatedEntryModules)) {
      for (const entryName of this.service.getRelatedEntryModules()!) {
        this.declareDepends(getTaskRealName({ name: taskName }, entryName).name);
      }
    } else {
      this.declareDepends(getTaskRealName({ name: taskName }).name);
    }
  }
}

export function getTaskRealName(taskDetail: TaskDetails, entryModuleName?: string): TaskDetails {
  if (entryModuleName) {
    return {
      ...taskDetail,
      name: `${taskDetail.name}With${capitalize(entryModuleName!)}`,
    };
  } else {
    return taskDetail;
  }
}
